package mytest.schedule;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONObject;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import mytest.util.JenkinsServer;
import test.driver.Base;
import test.runner.RunTest;
import test.service.ServiceJob;
import test.service.ServiceTestCase;
import test.service.ServiceTestModel;
import test.service.ServiceUser;
import test.testcase.TestCase;
import test.testcase.TestCaseData;
import test.testcase.TestJob;
import test.testcase.TestModel;
import test.testcase.dao.CaseCountDao;
import test.testcase.dao.JenkinsDao;
import test.testcase.dao.JobDao;
import test.testcase.dao.TestCaseDao;
import test.testcase.dao.TestModelDao;
import test.testcase.dao.TimerDao;
import test.testcase.dao.projectDao;
import test.user.user;
import test.utils.Config;
import test.utils.JsonResult;

@Component
public class Schedule {
	
	@Scheduled(cron = "0/5 * * * * ? ") // 在线执行测试用例
    public void taskCycle_testcase() {
		JsonResult result = TestCaseDao.getAnTestCaseExcutableJob();  //获取可执行的用例
		if (result.read("data[0]") == null) {
			return;
		}
		JSONObject object = result.read("data[0]").toJsonObject(); 
		if (object != null) {
			Base.loadConfig();
			String id = object.getString("testcaseid");
			String userid = object.getString("userid");
			user user = ServiceUser.getUser(userid);
			TestCase testcase = ServiceTestCase.getTestCase(id);
			TestCaseData data = ServiceTestCase.getTestDataByCaseId(id);  //用例测试数据
			RunTest runTestCase = new RunTest(Config.excute_method_online);  //在线方式执行
			runTestCase.setUser(user);
			TestCaseDao.startTestCaseExcuteJob(testcase, user);  //开始执行
			try {
				if (data == null) {  //如果不是测试数据驱动，只有一次执行
			   		runTestCase.excute(testcase, new HashMap<>());
			   	}else {  //如果是测试数据驱动，按测试数据配置循环执行
					List<Map<String, String>> testdata = data.getTestData();
					for (int i = 0; i < testdata.size(); i++) {
				   		runTestCase.excute(testcase, testdata.get(i));
					}
			   	}
				runTestCase.pass();  //执行通过
			} catch (Exception e) {
				runTestCase.error(e);  //执行异常
			}
		}
    }
	
	@Scheduled(cron = "0/5 * * * * ? ") //在线执行测试模型
    public void taskCycle_model() {
		JsonResult result = TestModelDao.getAnTestModelExcutableJob();
		JSONObject object = result.read("data[0]").toJsonObject();
		if (object != null) {
			Base.loadConfig();
			String id = object.getString("modelid");
			String userid = object.getString("userid");
			user user = ServiceUser.getUser(userid);
			TestModel model = ServiceTestModel.geTestModel(id);
			TestModelDao.delTestModelExcuteLog(model, user);
			TestModelDao.startTestModelExcuteJob(model, user);  //开始执行
			RunTest runTestCase = new RunTest(Config.excute_method_online);
			runTestCase.setUser(user);
			try {
				runTestCase.excute(model);
			} catch (Exception e) {
				runTestCase.error(e);
			}
			runTestCase.pass();
		}
    }
	
	@Scheduled(cron = "0/5 * * * * ? ") // 构建测试任务
    public void taskCycle_run() {
		TestJob job = ServiceJob.getAnPenddingJob();
		if (job == null) {
			return;
		}
		String projectid= JobDao.getJobByExcuteId(job.getExcuteid()).getProjectid();
		TestJob excutablejob = ServiceJob.getAnExecutableJob(projectid);
		if (excutablejob != null) {
			return;
		}
		JenkinsServer server = new JenkinsServer(projectid);
		String number = server.build();
		if (number != null) {
			if (Integer.valueOf(number) > 0) {
				JobDao.setJobBuildNumber(job, number);
				if (job.getId() != null) {
					JobDao.addAnExcuteJob(job);
				}else {
					JobDao.addAnExcuteProjectJob(job);
				}
			}
		}
    }
	
	@Scheduled(cron = "0/5 * * * * ? ") //定时任务扫描
    public void taskCycle_timer() {
		JsonResult result = TimerDao.getAnExcutableTime();
		JSONObject time = result.read("data[0]").toJsonObject();
		if (time != null) {
			String timerId = time.getString("id");
			JobDao.addAnPenddingJob(timerId);
			TimerDao.setTimerExcuted(timerId);
		}
	}
	
	@Scheduled(cron = "0/10 * * * * ? ") //异常执行任务扫描
    public void taskCycle_error() throws Exception {
		JsonResult result = JobDao.getAnExecutingJob();
		if ("".equals(result.read("").toString())) {
			return;
		}
		String id = result.read("data[0].projectid").toString();
		String buildnumber = result.read("data[0].buildnumber").toString();
		String excuteid = result.read("data[0].excuteid").toString();
		if (buildnumber == null || "".equals(buildnumber)) {
			return;
		}
		JenkinsServer server = new JenkinsServer(id);
		String reString = "";
		try {
			if (!server.getJob().details().getBuildByNumber(Integer.valueOf(buildnumber)).details().isBuilding()) {
				reString = server.getJob().details().getBuildByNumber(Integer.valueOf(buildnumber)).details().getResult().toString();
				if ("ABORTED".equals(reString) || "FAILURE".equals(reString)) {
					JobDao.endJobWithErr(JobDao.getJobByExcuteId(excuteid));
				}else {
					JobDao.endJob(JobDao.getJobByExcuteId(excuteid));
				}
			}
		} catch (Exception e) {
			JobDao.endJobWithErr(JobDao.getJobByExcuteId(excuteid));
		}
	}
	
	@Scheduled(cron= "0 0 10 * * ?")  //每天10点手机测试用例数
    public void deleteAllTempClob(){
		CaseCountDao.casecount();
	}

}
